<?php
namespace app\index\controller;
use think\Controller;
use think\Db;
use think\facade\Request;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

class Login extends Controller
{
    protected $middleware = ['Login'];

    /*
     * 用户登录
     * 新用户注册
     * */
    public function sign_in()
    {
        $params = Request::param('', '', 'strip_tags,trim');

        $UserLogic = \think\facade\App::model('User', 'logic');
        $resultLogin = $UserLogic->sign_in_app($params);

        return json($resultLogin);
    }
	
	
	public function mail_login()
	{
		$params = Request::param('', '', 'strip_tags,trim');
		$verify_result = $this->validate($params, 'Login.mail_login');

        if(true !== $verify_result){
            return json(['code'=>101,'msg'=>$verify_result]);
        }
		
		$record = Db::table('quick_email_code')->where('email',$params['email'])
		->where('code',$params['mail_code'])->field('create_time')->findOrEmpty();
		
		if(empty($record))
		{
			return json(['code'=>101,'msg'=>'The verification code is invalid. Please verify and fill it out again.']);
		}
		
		$diff = time()-strtotime($record['create_time']);
		
		if($diff > 180)
		{
			return json(['code'=>102,'msg'=>'The login verification code has expired, please resend it.']);
		}
		
		$UserLogic = \think\facade\App::model('User', 'logic');
        $resultLogin = $UserLogic->sign_in_email($params);

        return json($resultLogin);	
	}
	
	public function send_mail_code()
	{
		$params = Request::param('', '', 'strip_tags,trim');
		$verify_result = $this->validate($params, 'Login.send_code');

        if(true !== $verify_result){
            return json(['code'=>101,'msg'=>$verify_result]);
        }
		
		$record = Db::table('quick_email_code')->where('email',$params['email'])->field('create_time')->order(['id'=>'DESC'])->findOrEmpty();
		if($record)
		{
			$diff = time()-strtotime($record['create_time']);
			
			if($diff < 180)
			{
				return json(['code'=>101,'msg'=>'Please do not resend the verification code within its validity period']);
			}
		}
		
		$code = getNonceNumber(6);
		$str = "Hello! Your login verification code is 【 {$code} 】 , and the verification code is valid for three minutes.";
		
		$result = $this->send_mail($params['email'],'Login verification code',$str);
		
		if($result != 'success')
		{
			return json(['code'=>102,'msg'=>$result,'data'=>[]]);
		}
		
		Db::table('quick_email_code')->insert(['email'=>$params['email'], 'code'=> $code, 'create_time'=>date('Y-m-d H:i:s') ]);
		
		return json(['code'=>0,'msg'=>$result,'data'=>[]]);
	}
	
	private function send_mail($email,$subject,$message)
    {
		$config_mail = [
			'mail_host'     => 'smtp.163.com', //'smtp.163.com',
			'mail_port'     => '25',
			'mail_user'     => 'wlx_zong@163.com',
			'mail_pwd'      => 'CNfDadJqAMVFa8AP',
			'mail_debug'    => false,
		];
		
		
        $mail = new PHPMailer(true);

        try {
            //Server settings
            $mail->SMTPDebug = SMTP::DEBUG_OFF; //SMTP::DEBUG_SERVER;                      //Enable verbose debug output
            $mail->isSMTP();                                            //Send using SMTP
            $mail->Host       = $config_mail['mail_host'];                     //Set the SMTP server to send through
            $mail->SMTPAuth   = true;                                   //Enable SMTP authentication
            $mail->Username   = $config_mail['mail_user'];                     //SMTP username
            $mail->Password   = $config_mail['mail_pwd'];                               //SMTP password
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;            //Enable implicit TLS encryption
            $mail->Port       = 465;                                    //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`

            //Recipients
            $mail->setFrom($config_mail['mail_user'], 'User login verification');
            $mail->addReplyTo($config_mail['mail_user'], 'User login verification');
            $mail->AddAddress($email, $email);

            //Content
            $mail->isHTML(true);                                  //Set email format to HTML
            $mail->Subject = $subject;
            $mail->Body    = $message;
            //$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

            $mail->send();
			
			return 'success';
        } catch (Exception $e) {
            return "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
        }

    }
}

